package Reflect.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: zcw
 * @version: 1.0
 * 测试反射性能 和优化方案
 */
public class Demo02 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
     m1 ();
     m2 ();
     m3 ();
    }
    public static void m1(){
        Cat cat = new Cat ();
        long start = System.currentTimeMillis ();
        for(int i = 0; i < 900000000; i++){
            cat.hi ();
        }
        long end = System.currentTimeMillis ();
        System.out.println ("m1 时间为： "  + (end - start));
    }
    public static void m2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class cls = Class.forName ("Reflect.Test.Cat");
        Object o = cls.newInstance ();
        Method hi = cls.getMethod ("hi");
        long start = System.currentTimeMillis ();
        for(int i = 0; i < 900000000; i++){
            hi.invoke (o);
        }
        long end = System.currentTimeMillis ();
        System.out.println ("m2 时间为： "  + (end - start));
    }
    //反射优化 : 关闭访问检查
    public static void m3() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class cls = Class.forName ("Reflect.Test.Cat");
        Object o = cls.newInstance ();
        Method hi = cls.getMethod ("hi");
        hi.setAccessible (true); // 在反射调用方法时，取消访问检查
        long start = System.currentTimeMillis ();
        for(int i = 0; i < 900000000; i++){
            hi.invoke (o);
        }
        long end = System.currentTimeMillis ();
        System.out.println ("m3 时间为： "  + (end - start));
    }
}
